package com.ywyt.topic;

import com.rabbitmq.client.*;
import com.ywyt.util.ConnUtil;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class TopicConsumer1 {
    public static final String QUEUE1 = "topic-queue-1";
    public static final String QUEUE2 = "topic-queue-2";

    @Test
    public void receive() throws IOException, TimeoutException {
        //获取连接对象
        Connection conn = ConnUtil.getConnection();
        //获取channel
        final Channel channel = conn.createChannel();
        //声明队列1并绑定
        channel.queueDeclare(QUEUE1,false,false,false,null);
        channel.queueBind(QUEUE1,TopicProvider.EX_NAME,"#");

        //声明队列2并绑定
        channel.queueDeclare(QUEUE2,false,false,false,null);
        channel.queueBind(QUEUE2,TopicProvider.EX_NAME,"topic.*.order");

        //发布消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息" + new String(body,"UTF-8"));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(QUEUE1,false,consumer);
        channel.basicConsume(QUEUE2,false,consumer);

        System.in.read();
        channel.close();
        conn.close();
    }
}
